package com.mch.func.file.conver;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.RandomAccessFile;

import org.apache.commons.io.FileUtils;

/**
 * HTML==>>JSP
 */
public class TransferHtmlToJsp {

	public static void main(String[] args) {

		String filePath = "G:/Java/workspace/web_mybatis/WebContent";

		TransferFile(filePath);

		deleteHtmlFile(filePath);
	}

	public static void TransferFile(String filePath) {

		File file = new File(filePath);

		File[] fileList = file.listFiles();

		for (File fl : fileList) {

			String fileName = fl.getName();

			if (fileName.endsWith("html")) {

				String[] fileNameArr = fileName.split("\\.");

				File fi = new File(filePath + "/" + fileNameArr[0] + "." + "jsp");

				try {

					FileUtils.copyFile(fl, fi);

					String appendContext = "<%@ page language=\"java\" contentType=\"text/html;charset=UTF-8\" pageEncoding=\"UTF-8\" %>\n<%@ taglib prefix=\"c\" uri=\"http://java.sun.com/jsp/jstl/core\"%>\n";

					appendTo(fi, 0, appendContext);

				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}

	public static void appendTo(File fileName, long pos, String insertContent) throws IOException {

		File file = File.createTempFile("tmp", null);

		file.deleteOnExit();

		RandomAccessFile raf = new RandomAccessFile(fileName, "rw");

		FileInputStream fileInputStream = new FileInputStream(file);

		FileOutputStream fileOutputStream = new FileOutputStream(file);

		raf.seek(pos);

		byte[] buff = new byte[1];

		int hasRead = 0;

		while ((hasRead = raf.read(buff)) > 0) {
			fileOutputStream.write(buff);
		}

		raf.seek(pos);

		raf.write(insertContent.getBytes());

		while ((hasRead = fileInputStream.read(buff)) > 0) {
			raf.write(buff, 0, hasRead);
		}

		raf.close();
		fileInputStream.close();
		fileOutputStream.close();
	}

	public static void deleteHtmlFile(String filePath) {

		File file = new File(filePath);

		File[] fileList = file.listFiles();

		for (File fl : fileList) {

			if (fl.getName().endsWith("html")) {

				fl.delete();
			}
		}
	}
}
